var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var mysql = require("mysql2/promise"); // 使用promise版本
app.use(express.static("."));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // 添加JSON解析

// 使用连接池而不是单一连接
const pool = mysql.createPool({
    host: 'localhost',
    user: 'test',
    password: '123456',
    database: 'studentdb',
    port: 3307,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 测试数据库连
pool.getConnection()
    .then(conn => {
        console.log("数据库连接成功");
        conn.release();
    })
    .catch(err => {
        console.log("数据库连接失败", err);
    });
// 登录路由
app.post("/login", async (req, res) => {
    try {
        const { username, password } = req.body;
        
        if (!username || !password) {
            return res.status(400).json({ 
                success: false, 
                message: "用户名和密码不能为空" 
            });
        }
        
        const [results] = await pool.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [username, password]
        );
        
        if (results.length > 0) {
            res.json({ 
                success: true, 
                message: "登录成功",
                user: results[0] // 可以返回用户信息
            });
        } else {
            res.status(401).json({ 
                success: false, 
                message: "用户名或密码错误" 
            });
        }
    } catch (err) {
        console.error("登录错误:", err);
        res.status(500).json({ 
            success: false, 
            message: "服务器错误" 
        });
    }
});
app.post("/register", async (req, res) => {
    try {
        const { username, password } = req.body;
        console.log("注册请求数据:", { username, password }); // 调试日志
        
        if (!username || !password) {
            return res.status(400).json({ success: false, message: "用户名和密码不能为空" });
        }
        
        // 检查用户是否存在
        const [checkResults] = await pool.execute(
            'SELECT * FROM users WHERE username = ?',
            [username]
        );
        
        if (checkResults.length > 0) {
            return res.status(409).json({ success: false, message: "用户名已存在" });
        }
        
        // 插入新用户
        const [result] = await pool.execute(
            'INSERT INTO users (username, password) VALUES (?, ?)',
            [username, password]
        );
        console.log("插入结果:", result); // 调试日志
        
        res.json({ success: true, message: "注册成功" });
    } catch (err) {
        console.error("注册错误:", err);
        res.status(500).json({ success: false, message: "注册失败: " + err.message });
    }
});

app.listen(3000, (err) => {
    if (err) {
        console.error("服务器启动失败", err);
    } else {
        console.log("服务器启动成功!");
    }
});